from django.shortcuts import render
from django.template.loader import render_to_string
from django.http import HttpResponse, JsonResponse, FileResponse, HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import redirect
from django.views.generic import TemplateView
# Create your views here.


def hello_world(request):
    raise
    return HttpResponse('hello world')


def article_list(request, month):
    """
    :param month: 今年某一个月的文章
    """
    return HttpResponse('article: {}'.format(month))


def search(request):
    """GET参数的获取"""
    name = request.GET.get('name', '')
    print(name)
    return HttpResponse('查询成功')


def render_str(request):
    name = 'index.html'
    html = render_to_string(template_name=name)
    return HttpResponse(html)


def render_html(request):
    return render(request, 'index.html')


def http_request(request):
    """请求练习"""
    # 1.请求方式
    print(request.method)
    # 2.请求头信息
    headers = request.META
    # print(headers)
    ua = request.META.get('HTTP_USER_AGENT', None)
    print(request.headers)
    # print(ua)
    print(request.headers['User-Agent'])
    print(request.headers['user-Agent'])
    # 3.获取请求参数
    name = request.GET.get('name', '')
    print(name)
    return HttpResponse('响应')


def http_response(request):
    """响应练习"""
    # resp = HttpResponse('响应', status=201)
    # resp.status_code = 204
    # print(resp.status_code)

    # 响应json
    user_info = {
        'name': '张三',
        'age': 34
    }
    return JsonResponse(user_info)


def resp_file(request):
    # 响应图片
    resp = FileResponse(open('my_file.png', 'rb'))
    return resp


def no_data_404(request):
    """404页面"""
    return HttpResponse('404')


def article_detail(request, art_id):
    """
    文章详情,id从1000开始的整数
    """
    if art_id < 1000:
        # return HttpResponseRedirect('/hello/404')
        # return HttpResponseRedirect(reverse('no_data_404'))
        return redirect('no_data_404')  # 传递视图函数名称
    return HttpResponse('文章{}的内容'.format(art_id))


def index(request):
    return render(request, 'index.html')


class HomeView(TemplateView):
    template_name = 'home.html'
